package reflect;

import java.io.File;
import java.net.URISyntaxException;
import java.nio.file.Files;

/**
 * 实例化与当前类Test所在的同一个包中的每个类的实例(使用无参构造器)
 */
public class Test {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException {
//        File dir = new File(
//                Test.class.getResource(".").toURI()
//        );
//        File[] files = dir.listFiles(f->f.getName().endsWith(".class"));
//        for(File file:files){
//            String[] data = file.getName().split("\\.");
//            Class cls = Class.forName(dir.getName()+"."+data[0]);
//            Object obj = cls.newInstance();
//            System.out.println(obj);
//        }
        Class cls = Test.class;
        File dir = new File(
                cls.getResource(".").toURI()
        );
        //通过类对象获取其所在的包的名字
        String packageName = cls.getPackage().getName();
        System.out.println(packageName);

        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for(File sub:subs){
            String fileName = sub.getName();
            String className = fileName.substring(0,fileName.indexOf("."));

            className = packageName+"."+className;
            Class c = Class.forName(className);
            Object obj = c.newInstance();
            System.out.println(obj);
        }
        System.out.println(dir);
    }
}
